package com.zxx.xin.shorthand.helper;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.View;
import android.view.WindowManager;
import android.widget.HorizontalScrollView;

import java.io.ByteArrayOutputStream;
import java.io.File;

/**
 * Created by xin on 2018/3/21.
 */

public class BitmapHleper {

    public static Bitmap generateBitmapFromHorizontalScrollView(HorizontalScrollView view){
        int width = view.getChildAt(0).getWidth() > view.getWidth() ? view.getChildAt(0).getWidth() : view.getWidth();
        int height = view.getHeight();
        view.layout(0, 0, width, height);
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);
        view.draw(canvas);
        return bitmap;
    }

    public static byte[] bitmapToByteArray(Bitmap bitmap, int quality){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, quality, baos);
        return baos.toByteArray();
    }

    public static Bitmap byteArrayToBitmap(byte[] data){
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
        return bitmap;
    }

    public static Bitmap getBitmapByFilePath(Context context, String filePath, int defaultImageId){

        if(filePath == null){
            return BitmapFactory.decodeResource(context.getResources(), defaultImageId);
        }

        File file = new File(filePath);
        Bitmap bitmap = null;
        if (!file.exists()){
            bitmap = BitmapFactory.decodeResource(context.getResources(), defaultImageId);
        } else {
            bitmap = BitmapFactory.decodeFile(filePath);
        }
        return bitmap;
    }

}
